<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button
          type="primary"
          style="float: left; padding: 10px 10px"
          @click="open"
          >创建用户</el-button
        >
      </div>
      <template>
        <el-table :data="list" border style="width: 100%">
          <el-table-column prop="username" label="用户名" width="180">
          </el-table-column>
          <el-table-column prop="email" label="邮箱" width="180">
          </el-table-column>
          <el-table-column prop="phone" label="电话"> </el-table-column>
          <el-table-column prop="create_time" label="注册时间">
              <template slot-scope="scope">
                    {{new Date(scope.row.create_time).toLocaleString()}}
                </template>
          </el-table-column>
          <el-table-column prop="role_id" label="权限角色">
              <template slot-scope="scope">
                    {{getRole(scope.row.role_id)}}
                </template>
          </el-table-column>
          <el-table-column prop="address" label="操作">
            <template slot-scope="scope">
              <el-button size="mini" @click="openAddUserBox(scope.row)"
                >修改</el-button
              >
              <el-button size="mini" @click="deleteUser(scope.row._id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
      <div style="text-align: center">
        <el-pagination
          class="pagination"
          background
          layout="prev, pager, next"
          :total="total"
          @current-change="current_change"
          :page-size="pageSize"
          @next-click="handlenext"
          @prev-click="handleprev"
        >
        </el-pagination>
      </div>
      <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogFormVisible"
        @close="resetForm"
      >
        <el-form :model="form" :rules="rules" ref="ruleForm">
          <el-form-item
            label="用户名"
            :label-width="formLabelWidth"
            prop="username"
          >
            <el-input v-model="form.username" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item
            label="密码"
            v-if="pwdShow"
            :label-width="formLabelWidth"
            prop="password"
          >
            <el-input v-model="form.password" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item
            label="手机号"
            :label-width="formLabelWidth"
            prop="phone"
          >
            <el-input v-model="form.phone" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
            <el-input v-model="form.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="角色"
            :label-width="formLabelWidth"
            prop="role_id"
          >
            <el-select v-model="form.role_id" placeholder="请选择用户权限角色">
              <el-option
                v-for="(role, index) in roles"
                :key="index"
                :label="role.name"
                :value="role._id"
                
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="exitAdd">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import { getuser,adduser,getrole,deluser,updateuser } from "../api/index";
export default {
  data() {
    return {
      user: {},
      list: [],
      roles:[],
      loading: false, //加载动画
      parentId: 0,
      pageNum: 1,
      pageSize: 5,
      total: 0,
      name: "",
      username:"",
      passwor:"",
      phone:"",
      email:"",
      role_id:"",
      adduserdata:{},
      dialogFormVisible: false,
      dialogTitle: "",
      pwdShow: true,
      form: {
        username: "",
        password: "",
        phone: "",
        email: "",
        role_id: "",
      },
      formLabelWidth: "120px",
      rules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            min: 2,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            min: 2,
            max: 10,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            pattern: /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/,
            message: "请输入正确的手机号格式",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          {
            pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            message: "请输入正确的邮箱格式",
            trigger: "blur",
          },
        ],
        role_id: [
          {
            required: true,
            message: "请选择权限角色",
            trigger: "blur",
          },
        ],
      },
    };
  },
  async mounted() {
    let { data } = await getuser({
      pageNum: this.pageNum,
      pageSize: this.pageSize,
    });
    this.user = data.data;
    this.list = data.data.list;
    this.total = data.data.total;
    let {data:res}= await getrole()
    this.$store.commit("GET_ROLES",res.data.list)
    this.roles=this.$store.state.roles
  },
  methods: {
    resetForm() {
      
    },
    current_change(val) {
      this.pageNum=val
      this.getuser(val);
    },
    async getuser(val) {
      let { data } = await getuser({
        pageNum: val,
        pageSize: this.pageSize,
      });
      this.user = data.data;
      this.list = data.data.list;
      this.total = data.data.total;
    },
    async adduser() {
      let { data } = await adduser({
        username: this.username,
        password: this.password,
        phone:this.phone,
        email:this.email,
        role_id:this.role_id
      });
      this.adduserdata=data.data
    },
    async deluser(id) {
      await deluser({
        userId:id
      });
      
    },
    async updateuser() {
      await updateuser(this.form);
      
    },
    handlenext(val) {
      this.pageNum=val
      this.getuser(val);
    },
    handleprev(val) {
      this.pageNum=val
      this.getuser(val);
    },
    open() {
      this.dialogFormVisible = true;
      
      
    },

      addUser() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false;
          this.username=this.form.username
          this.password=this.form.password
          this.phone=this.form.phone
          this.email=this.form.email
          
          if(this.dialogTitle=="添加用户"){
            this.adduser()
          }else{
            this.updateuser()
            this.getuser(this.pageNum)
          }

        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    exitAdd() {
      this.dialogFormVisible = false;
      this.$refs["ruleForm"].resetFields();
      for (let prop in this.form) {
        this.form[prop] = "";
      }
    },
    getRole(id){
        let obj=this.$store.state.roles.find((item)=>{
            return item._id==id
        })
        if(obj){
          return obj.name
        }else
        return 
        
    },
    deleteUser(id){
        this.deluser(id)
        this.getuser(this.pageNum)
    },
    openAddUserBox(obj){
        this.dialogFormVisible = true
                if (obj && obj._id) {
                    this.pwdShow = false;
                    this.dialogTitle = '修改用户';
                    const {_id, username, email, phone, role_id} = obj;
                    this.form = {
                        _id,
                        username,
                        phone,
                        email,
                        role_id
                    }

                } else {
                    this.pwdShow = true;
                    this.dialogTitle = '添加用户'
                }
    }
    
  },
  
};
</script>